package com.filter;

import com.entity.User;
import com.util.IfLogin;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author admin
 */
public class LoginIn implements Filter {
    //获取允许通过的访问页面

   private String[] through;

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //获取请求路径
        String path = ((HttpServletRequest)req).getServletPath();
        if(!IfLogin.isLogin(through,path)){     //如果请求路径是否存在于通行数组中.如果不是则判断
            //是否为LoginServlet.filter发来的请求
            User user = (User) ((HttpServletRequest) req).getSession().getAttribute("user");
            if(user == null){
                ((HttpServletResponse)resp).sendRedirect(((HttpServletRequest) req).getContextPath()+"/login.jsp");
                return;
            }
        }
        chain.doFilter(req, resp);
    }

    @Override
    public void init(FilterConfig config) {
        through =  config.getInitParameter("loginPath").split(",");
    }

}
